package com.agent;

import com.agent.domain.AgentInfo;
import com.agent.domain.AgentInfoMapper;
import com.agent.util.AppUtil;
import com.agent.util.DBUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayDeque;
import java.util.Deque;

@Slf4j
public class MethodMonitor {
    private static final ThreadLocal<Deque<String>> callStack = ThreadLocal.withInitial(ArrayDeque::new);

    /**
     * 方法进入
     * @param className
     * @param methodName
     * @param traceId
     */
    public static void methodEntry(String className, String methodName, String traceId) {
        String fullMethod = className + "#" + methodName;
        callStack.get().push(fullMethod);
       // log.info("进入方法=>"+fullMethod +"  traceId=>"+traceId);
    }

    /**
     * 方法退出
     * @param className
     * @param methodName
     * @param durationMs
     * @param exception
     */
    public static void methodExit(String className, String methodName,
                                  long durationMs, Throwable exception) {
        String fullMethod = className + "#" + methodName;
        callStack.get().pop();
        String status = exception != null ? "ERROR" : "SUCCESS";
       /* String logMsg = String.format("[EXIT] %s | %s | %dms", fullMethod, status, durationMs);
        log.info("退出方法=>"+logMsg);*/
        //超过一定时间记录日志
        AgentInfoMapper agentInfoMapper = DBUtil.getSession().getMapper(AgentInfoMapper.class);
        AgentInfo agentInfo = new AgentInfo();
        agentInfo.setServerName(AppUtil.getAppName());
        agentInfo.setServerId(AppUtil.serverIp());
        agentInfo.setClassName(className);
        agentInfo.setFunctionName(methodName);
        agentInfo.setCostTime((int)durationMs);
        agentInfo.setResult(status);
        agentInfoMapper.insertAgentInfo(agentInfo);
        log.info("接口耗时达到阈值:{}",fullMethod);

    }
}